/**
 * Copyright (c) 2012, Camelot and/or its affiliates. All rights reserved.
 * Camelot PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.camelot.ccr.global.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.camelot.ccr.global.util.Pager;
import com.camelot.ccr.global.util.Utility;

/**
 * <pre>
 * 基类controller
 * </pre>
 * 
 * @author Liu Jun
 * @version V0.1, 2013-12-26 下午2:36:53
 */
public class BaseController{

	
	/**
	 * fastjson配置
	 */
	private static SerializeConfig mapping = new SerializeConfig();
	private static Calendar c = Calendar.getInstance();	
	public static final String CURRENT_USER = "currentUser";
	static {
		mapping.put(Date.class, new SimpleDateFormatSerializer(Utility.DATE_DEFAULT_PATTERN));
	}

	/**
	 * <pre>
	 * Ajax输出FastJosn
	 * </pre>
	 * 
	 * @param o
	 *            要转成json的对象
	 * @param response
	 *            输出对象
	 * @throws IOException
	 *             拋出IOExcepton
	 * @author Liu Jun, 2013-12-26 下午2:44:46
	 */
	protected void ajaxOutJsonObject(Object o, HttpServletResponse response)throws IOException {
		if (Utility.isNotEmpty(o)) {
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter pw = response.getWriter();
			pw.append(JSON.toJSONString(o, mapping));
			pw.close();
		}
	}
	
	/**
	 * <pre>
	 * Ajax输出FastJosn
	 * </pre>
	 * 
	 * @param o
	 *            要转成json的对象
	 * @param response
	 *            输出对象
	 * @throws IOException
	 *             拋出IOExcepton
	 * @author Liu Jun, 2013-12-26 下午2:44:46
	 */
	protected void ajaxOutJsonObjectCloseIndex(Object o, HttpServletResponse response)throws IOException {
		if (Utility.isNotEmpty(o)) {
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter pw = response.getWriter();
			pw.append(JSON.toJSONString(o, mapping,SerializerFeature.DisableCircularReferenceDetect));
			pw.close();
		}
	}
	

	/**
	 * <pre>
	 * 将分页对象转换为符合easyui的datagrid的json数据
	 * </pre>
	 * @param pager 包含总记录数和dataList
	 * @param response 输出流
	 * @return null
	 * @author chendd, 2013-12-26 下午6:08:34
	 * @throws IOException response输出流
	 */
	protected String pager2Json(Pager<?> pager , HttpServletResponse response) throws IOException{
		
		JSONObject json = new JSONObject();
		json.put("total", pager.getSum());
		json.put("rows", pager.getSearchList());
		ajaxOutJsonObject(json, response);
		return null;
	}
	
	/**
	 * <pre>
	 * 将分页对象转换为符合easyui的datagrid的json数据
	 * </pre>
	 * @param pager 包含总记录数和dataList
	 * @param response 输出流
	 * @return null
	 * @author chendd, 2013-12-26 下午6:08:34
	 * @throws IOException response输出流
	 */
	protected String pager2JsonCloseIndex(Pager<?> pager , HttpServletResponse response) throws IOException{
		
		JSONObject json = new JSONObject();
		json.put("total", pager.getSum());
		json.put("rows", pager.getSearchList());
		ajaxOutJsonObjectCloseIndex(json, response);
		return null;
	}

	/**
	 * <pre>
	 * 获得当前session用户
	 * </pre>
	 * @param request request
	 * @return User
	 * @author Liu Jun, 2014-1-9 上午10:54:32
	 */
	/*protected User getSessionUser(HttpServletRequest request){
		HttpSession session = request.getSession();
		User u = (User) session.getAttribute(BaseController.CURRENT_USER);
		return u;
	}*/
	
	
	
	/**
	 * <pre>
	 * 获取当前年份
	 * </pre>
	 * @return
	 * @author Li Hong, Apr 2, 2014 1:06:14 PM
	 */
	protected int getCurrentYear(){
		int year = c.get(Calendar.YEAR);
		return year;
	}
	
	/**
	 * <pre>
	 * 获取当前月份
	 * </pre>
	 * @return
	 * @author Li Hong, Apr 2, 2014 1:06:27 PM
	 */
	protected int getCurrentMonth(){
		int month = c.get(Calendar.MONTH)+1;
		return month;
	}
	
	
	/**
	 * <pre>
	 * 获取年份集合
	 * </pre>
	 * @return
	 * @author Li Hong, Apr 2, 2014 1:07:03 PM
	 */
	protected List<Integer> getListYear(){
		List<Integer> listYear = new ArrayList<Integer>();
		for(int i=0;i<=10;i++){
			listYear.add(this.getCurrentYear()-i);
		}
		return listYear;
	}
	
	/**
	 * <pre>
	 * 获取月份集合
	 * </pre>
	 * @return
	 * @author Li Hong, Apr 2, 2014 1:07:14 PM
	 */
	protected List<Integer> getListMonth(){
		List<Integer> listMonth = new ArrayList<Integer>();
		for(int i=1;i<=12;i++){
			listMonth.add(i);
		}
		return listMonth;
	}
	
	
	/**
	 * 
	 * <pre>
	 * 根据request对象获取到前台传递的参数,并转换成Map<String, Object>格式
	 * </pre>
	 * @param request 请求内置对象
	 * @return JSONObject JSONObject格式的数据
	 * @author Niu Lina, 2014-2-13 下午5:30:51
	 */
	protected JSONObject convertMap(HttpServletRequest request)
	{
	    Map<String, String[]> paramMap = request.getParameterMap();
	    if(Utility.isNotNull(paramMap)) {
	    	Map<String, String> tempMap = new HashMap<String, String>();
	        Set<Entry<String, String[]>> keySet = paramMap.entrySet();
	        Iterator<Entry<String, String[]>> keyIter = keySet.iterator();
	        while(keyIter.hasNext())
	        {
	        	Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) keyIter.next( );
	        	String key = entry.getKey();
	        	String[] valueArr = entry.getValue();
	        	if(Utility.isNotNull(valueArr) && valueArr.length > 0)
	        	{
	        		int length = valueArr.length;
	        		if(length == 1)
	        		{
	        			tempMap.put(key, valueArr[0]);
	        		} else {
	        			StringBuilder bufferStr = new StringBuilder();
	        			for(int i = 0; i < length; i++) {
	        				if(i == length - 1)
	        				{
	        					bufferStr.append(valueArr[i]);
	        				} else {
	        					bufferStr.append(valueArr[i]).append(",");
	        				}
	        			}
	        			tempMap.put(key, bufferStr.toString());
	        		}
	        	}
	        }
	        JSONObject jsonParam = new JSONObject();
		    jsonParam.putAll(tempMap);
		    return jsonParam;
	    }
	    return null;
	}
	
}
